﻿using System;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using Tools;
using WPF数据采集系统.Base;
using WPF数据采集系统.Model;
using WPF数据采集系统.ViewModel;

namespace WPF数据采集系统.View
{
    /// <summary>
    /// SystemSetView.xaml 的交互逻辑
    /// </summary>
    public partial class SystemSetView : UserControl
    {
        public SystemSetView()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            string sql = "select id as '序号',user_name as '用户名',role as '所属角色',DateTime as '日期',is_valid as '是否有效'  from Users";
            DataTable dt = SqlHelper.GetDataSet(sql).Tables[0];
            dataGrid.ItemsSource = dt.DefaultView;

            //defaultView
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            autoOperator.IsChecked = Convert.ToBoolean(PlcTool.IniRead("SystemDefault", "自动操作员登录", path + "\\OmronPLCAddress.ini"));
            autoStartup.IsChecked = Convert.ToBoolean(PlcTool.IniRead("SystemDefault", "开机自动运行", path + "\\OmronPLCAddress.ini"));

            string model = PlcTool.IniRead("SystemDefault", "旋转机默认规格", path + "\\OmronPLCAddress.ini");
            m_v_name.Text = model;
            string project = PlcTool.IniRead("Project", "默认项目", path + "\\OmronPLCAddress.ini");
            switch (project)
            {
                case ViewName.MainViewName:
                    project = "圆柱旋转机";
                    break;
                case ViewName.MainViewHotPress:
                    project = "半自动热压机";
                    break;
            }
            m_v_pname.Text = project;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //添加用户
            string uname = user_name.Text.Trim();
            string psd = password.Password;
            string sqlrole = role.Text;
            if (string.IsNullOrWhiteSpace(uname) || uname.Length < 2)
            {
                CustomMsgBox.ShowDialog("用户名长度不足异常", "用户名不能为空并且长度不能小于2", CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                return;
            }
            if (psd.Length < 3 || psd.Contains(" "))
            {
                CustomMsgBox.ShowDialog("密码设置异常", "请检查密码长度不能小于3并且密码不应包含'空格符'", CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                return;
            }
            if (string.IsNullOrWhiteSpace(sqlrole))
            {
                CustomMsgBox.ShowDialog("用户角色选择异常", "角色不能为空,请检查", CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                return;
            }
            string sql = "INSERT  into Users(user_name,password,DateTime,role,is_valid) values('" + uname + "','" + DESEncrypt.Encrypt(psd) + "','" + DateTime.Now.ToLocalTime() + "','" + sqlrole + "'," + 1 + ")";
            try
            {
                SqlHelper.Update(sql);
                CustomMsgBox.ShowDialog("Successful", "用户添加成功！", CustomMsgBoxButton.One, CustomMsgBoxImage.Success);
                string sql1 = "select id as '序号',user_name as '用户名',role as '所属角色',DateTime as '日期',is_valid as '是否有效'  from Users";
                DataTable dt = SqlHelper.GetDataSet(sql1).Tables[0];
                dataGrid.ItemsSource = dt.DefaultView;
            }
            catch (Exception ex)
            {
                CustomMsgBox.ShowDialog("用户角色选择异常", ex.Message, CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //删除用户
            DataRowView selectItem = dataGrid.SelectedItem as DataRowView;
            if (selectItem == null)
            {
                CustomMsgBox.ShowDialog("用户选择异常", "未选中任何用户，无法执行删除操作,请检查!", CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                return;
            }
            string id = selectItem.Row[0].ToString();

            if (CustomMsgBox.ShowDialog("删除警告", "删除操作不可逆,是否确认删除？", CustomMsgBoxButton.One, CustomMsgBoxImage.Error).IsYes)
            {
                if (int.Parse(id) < 4)
                {
                    CustomMsgBox.ShowDialog("删除失败", "系统内置用户禁止删除!", CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                    return;
                }
                string sql = "Delete Users where id=" + int.Parse(id);
                try
                {
                    SqlHelper.Update(sql);
                    CustomMsgBox.ShowDialog("删除成功", "删除操作执行成功:" + id, CustomMsgBoxButton.One, CustomMsgBoxImage.Success);
                    string sql1 = "select id as '序号',user_name as '用户名',role as '所属角色',DateTime as '日期',is_valid as '是否有效'  from Users";
                    DataTable dt = SqlHelper.GetDataSet(sql1).Tables[0];
                    dataGrid.ItemsSource = dt.DefaultView;
                }
                catch (Exception ex)
                {
                    CustomMsgBox.ShowDialog("删除失败", ex.Message, CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                }
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            //禁用用户
            DataRowView selectItem = dataGrid.SelectedItem as DataRowView;
            if (selectItem == null)
            {
                CustomMsgBox.ShowDialog("用户选择异常", "未选中任何用户，无法执行禁用操作,请检查!", CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                return;
            }
            string id = selectItem.Row[0].ToString();
            string sql = "Update Users set is_valid=" + 0 + " where id=" + int.Parse(id);
            try
            {
                SqlHelper.Update(sql);
                CustomMsgBox.ShowDialog("禁用用户成功", "禁用成功:" + id, CustomMsgBoxButton.One, CustomMsgBoxImage.Success);
                string sql1 = "select id as '序号',user_name as '用户名',role as '所属角色',DateTime as '日期',is_valid as '是否有效'  from Users";
                DataTable dt = SqlHelper.GetDataSet(sql1).Tables[0];
                dataGrid.ItemsSource = dt.DefaultView;
            }
            catch (Exception ex)
            {
                CustomMsgBox.ShowDialog("用户选择异常", ex.Message, CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            DataRowView selectItem = dataGrid.SelectedItem as DataRowView;
            if (selectItem == null)
            {
                CustomMsgBox.ShowDialog("用户选择异常", "无法执行获取密码操作,请检查!", CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                return;
            }
            string id = selectItem.Row[0].ToString();
            try
            {
                string sql = "select password from Users where id=" + int.Parse(id);
                Object result = SqlHelper.GetSingleResult(sql);
                if (result != null)
                {
                    string password = DESEncrypt.Decrypt(result.ToString().Trim());
                    CustomMsgBox.ShowDialog("Successful", "当前选中用户的密码为:[" + password + "](不含方括号)", CustomMsgBoxButton.One, CustomMsgBoxImage.Success);
                }
            }
            catch (Exception ex)
            {
                CustomMsgBox.ShowDialog("异常", ex.Message, CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
            }
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            DataRowView selectItem = dataGrid.SelectedItem as DataRowView;
            if (selectItem == null)
            {
                CustomMsgBox.ShowDialog("用户选择异常", "未选中任何用户，无法执行禁用操作,请检查!", CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                return;
            }
            string id = selectItem.Row[0].ToString();
            string sql = "Update Users set is_valid=" + 1 + " where id=" + int.Parse(id);
            try
            {
                SqlHelper.Update(sql);
                CustomMsgBox.ShowDialog("Successful", "启用用户成功：" + id, CustomMsgBoxButton.One, CustomMsgBoxImage.Success);
                string sql1 = "select id as '序号',user_name as '用户名',role as '所属角色',DateTime as '日期',is_valid as '是否有效'  from Users";
                DataTable dt = SqlHelper.GetDataSet(sql1).Tables[0];
                dataGrid.ItemsSource = dt.DefaultView;
            }
            catch (Exception ex)
            {
                CustomMsgBox.ShowDialog("异常", ex.Message, CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
            }
        }

        private void dataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DataGrid dg = sender as DataGrid;
            DataGridTemplateColumn templeColumn1 = dg.Columns[3] as DataGridTemplateColumn;
            FrameworkElement fwElement1 = dg.Columns[3].GetCellContent(dg.CurrentItem);
            DataRowView drv = fwElement1.DataContext as DataRowView;
            user_name.Text = drv.Row[1].ToString();
            role.Text = drv.Row[2].ToString();
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            string uname = user_name.Text.Trim();
            string pwd = password.Password.Trim();
            string roleEdit = role.Text.Trim();

            string check = "select user_name from Users where user_name='" + uname + "'";
            object user = SqlHelper.GetSingleResult(check);
            if (user == null)
            {
                CustomMsgBox.ShowDialog("异常", " 用户名不存在, 请检查！(用户名不允许修改)", CustomMsgBoxButton.One, CustomMsgBoxImage.Error);
                return;
            }
            string sql = "update Users set password='" + DESEncrypt.Encrypt(pwd) + "',role='" + roleEdit + "' where user_name='" + uname + "'";
            SqlHelper.Update(sql);
            CustomMsgBox.ShowDialog("Successful", "密码 / 角色修改成功!", CustomMsgBoxButton.One, CustomMsgBoxImage.Success);
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            ComboBox cmb = m_v_name as ComboBox;
            TextBox tb = cmb.Template.FindName("ctext", cmb) as TextBox;
            string model = tb.Text.Trim();

            ComboBox cmb1 = m_v_pname as ComboBox;
            TextBox tb1 = cmb1.Template.FindName("ctext", cmb1) as TextBox;
            string project = tb1.Text.Trim();
            switch(project)
            {
                case "圆柱旋转机":
                    project = ViewName.MainViewName;
                    break;
                case "半自动热压机":
                    project = ViewName.MainViewHotPress;
                    break;
            }
            PlcTool.IniWrite("Project", "默认项目", project, path + "\\OmronPLCAddress.ini");
            PlcTool.IniWrite("SystemDefault", "旋转机默认规格", model, path + "\\OmronPLCAddress.ini");
            PlcTool.IniWrite("SystemDefault", "自动操作员登录", autoOperator.IsChecked.ToString(), path + "\\OmronPLCAddress.ini");
            PlcTool.IniWrite("SystemDefault", "开机自动运行", autoStartup.IsChecked.ToString(), path + "\\OmronPLCAddress.ini");
            CustomMsgBox.ShowDialog("Successful", "保存成功！(Successful!)", CustomMsgBoxButton.One, CustomMsgBoxImage.Success);
            MainWindow.RotateModel = model;
            //MainWindow.mvm.RotateListInIt();
            AutoStart auto = new AutoStart();
            if (Convert.ToBoolean(autoStartup.IsChecked.ToString()))
            {
                auto.SetMeAutoStart(true);
            }
            else
            {
                auto.SetMeAutoStart(false);
            }
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            AutoStart auto = new AutoStart();
            if (auto.NowCreateDesktopQuick())
            {
                CustomMsgBox.ShowDialog("创建快捷方式成功!", "桌面路径：(" + auto.desktopPath + ") 图标名称:" + AutoStart.QuickName, CustomMsgBoxButton.One, CustomMsgBoxImage.Success);
            }
            else
            {
                CustomMsgBox.ShowDialog("创建快捷方式失败", "桌面已经存在快捷方式,请确认" + "桌面路径：(" + auto.desktopPath + ") 图标名称:" + AutoStart.QuickName);
            }
        }
    }
}
